/**
 * 
 */
package cn.boysoft.core.parse.impl;

import java.io.IOException;
import java.io.StringWriter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import cn.boysoft.core.exception.JEEException;
import cn.boysoft.core.exception.JsonParseException;
import cn.boysoft.core.model.message.json.JSONRequest;
import cn.boysoft.core.parse.ParseToRequest;
import cn.boysoft.core.server.MainServer;
import cn.boysoft.core.server.ServiceInfo;
import cn.boysoft.core.util.JsonUtil;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author 付厚俊
 * CreateTime 2013-4-4 上午11:24:15
 */
@Service(value="parseJsonToRequest")
public class ParseJsonToRequestImpl implements ParseToRequest {
	private final static Logger LOGGER = LoggerFactory.getLogger(ParseJsonToRequestImpl.class);
	@SuppressWarnings("unchecked")
	@Override
	public JSONRequest parseToRequest(String json) {
		 JSONRequest request = null;
		 ObjectMapper objectMapper =  new ObjectMapper();
		 try {
			request = objectMapper.readValue(json, JSONRequest.class);
			String commandId = request.getServiceId();
			ServiceInfo serviceInfo = MainServer.getOnlyReadServiceInfo(commandId);
			if(serviceInfo != null){
				Object data = request.getData();
				if(data != null){
					 StringWriter stringWriter = new StringWriter();
					 objectMapper.writeValue(stringWriter, data);
					 Class dataClazz = serviceInfo.getDataClazz();
					 if(dataClazz != null){
						 data = objectMapper.convertValue(data, dataClazz);
						 request.setData(data);
					 }else{
						 request.setData(null);
					 }
				}
			}else{
				throw new JEEException(JEEException.NOT_FIND_SERVICE);
			}
		}catch (JsonGenerationException e) {
			    LOGGER.error(JEEException.JSON_PARSE_ERROR, e);
				throw new JsonParseException(JEEException.JSON_PARSE_ERROR);
		} catch (JsonMappingException e) {
			
			LOGGER.error(JEEException.JSON_PARSE_ERROR, e);
			throw new JsonParseException(JEEException.JSON_PARSE_ERROR);
		} catch (IOException e) {
			LOGGER.error(JEEException.JSON_PARSE_ERROR, e);
			throw new JsonParseException(JEEException.JSON_PARSE_ERROR);
		}
		LOGGER.debug("Parse Data :"+JsonUtil.formatJson(JsonUtil.toJson(request)));
		return request;
	}

	public static void main(String[] args){
//		ParseToJsonRequestImpl parseToJsonRequestImpl = new ParseToJsonRequestImpl();
//		String jsonStr = "{\"data\":{\"name\":\"fuhoujun\",\"list\":[{\"name\":\"hello\"}],\"child\":{\"name\":\"hello\"}},\"op\":null,\"operateId\":null}";
//		JSONRequest request = parseToJsonRequestImpl.parseToJSONRequest(jsonStr, Person.class);
//		System.out.print(request);
	}
}
